using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [Header("移动参数")]
    public float moveSpeed = 5f;
    public float rotateSpeed = 180f;

    [Header("引用")]
    public CharacterController characterController;
    public GameManager_1 gameManager;

    private void Start()
    {
        if (characterController == null)
            characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        // 玩家移动
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        
        Vector3 moveDirection = new Vector3(horizontal, 0, vertical);
        moveDirection = transform.TransformDirection(moveDirection);
        characterController.SimpleMove(moveDirection * moveSpeed);
        
        // 玩家旋转
        if (moveDirection != Vector3.zero)
        {
            Quaternion toRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotateSpeed * Time.deltaTime);
        }
    }

    // 触发区域检测
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("GameArea"))
        {
            gameManager.isInGameArea = true;
            gameManager.uiManager.ShowGameAreaPanel();
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("GameArea"))
        {
            gameManager.isInGameArea = false;
            gameManager.uiManager.HideGameAreaPanel();
            
            // 如果正在游戏中，退出游戏
            if (gameManager.isPlaying)
            {
                gameManager.ResetGame();
                gameManager.uiManager.HideGameUI();
            }
        }
    }
}